#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    server = new QTcpServer(this);


    // 开启监听
    bool result = server->listen(QHostAddress::Any,8889);
    if(!result)
    {
        qDebug()<<"监听失败";
        return;
    }
    qDebug()<<"监听成功";
    connect(server,SIGNAL(newConnection()),this,SLOT(newConnectionSlot()));
    connect(ui->pushButton,&QPushButton::clicked,this,&Dialog::btnOneSlot);
    connect(ui->pushButton_2,&QPushButton::clicked,this,&Dialog::btnTwoSlot);
    connect(ui->pushButton_3,&QPushButton::clicked,this,&Dialog::btnTrhSlot);


}

Dialog::~Dialog()
{
    // 关闭监听
    if(server->isListening())   // 判断是否正在监听
    {
        server->close();
    }
    delete ui;
}

void Dialog::newConnectionSlot()
{
    // 如果不是第一次连接，就踢掉上一个人
    if(socket != NULL)
    {
        // 踢掉上一个人
        socket->close();
    }
    // 保存当前的连接对象
    socket = server->nextPendingConnection();

    // 断开连接信号槽
    connect(socket,SIGNAL(disconnected()),
            this,SLOT(disconnectSlot()));

    // 连接数据流处理信号槽
    connect(socket,SIGNAL(readyRead()),
            this,SLOT(readyReadSlot()));

    // 获取对面的IP地址
    QString ip = socket->peerAddress().toString();

    // 获取对面的端口号
    quint16 port = socket->peerPort();


    // 字符串拼接
    ip.prepend("新连接来啦！！！").append(":")
            .append(QString::number(port));
    qDebug()<<ip;

}

void Dialog::disconnectSlot()
{
    qDebug()<<"老链接走了";
}

void Dialog::readyReadSlot()
{
    // 读取所有的内容
    QByteArray buffer = socket->readAll();
    const char* text = buffer.constData();
    // 显示
    qDebug()<<text;
    // 定义变量存储温湿度
    temperature = 0.0;
    humidity = 0.0;
    // 使用 sscanf 解析字符串
    sscanf(text, "mode:%d, temperature:%f, humidity:%f",&mode,&temperature,&humidity);
    temperatureStr = QString::number(temperature);
    humidityStr = QString::number(humidity);
    ui->label_th->setText(temperatureStr);
    ui->label_ph->setText(humidityStr);
    if(mode == 1)
    {
        ui->label_3->setText("当前模式：除湿");
    }
    else if(mode ==2)
    {
        ui->label_3->setText("当前模式：控温");
    }
    else if(mode ==3)
    {
        ui->label_3->setText("当前模式：手动");
    }
}

void Dialog::btnOneSlot()
{
     str ="one";
     QByteArray buffer1 = str.toUtf8();
     // 发送
     socket->write(buffer1);
}

void Dialog::btnTwoSlot()
{
    str ="two";
    QByteArray buffer1 = str.toUtf8();
    // 发送
    socket->write(buffer1);
}

void Dialog::btnTrhSlot()
{
    str ="three";
    QByteArray buffer1 = str.toUtf8();
    // 发送
    socket->write(buffer1);
}

